<template>
  <div
    class="buildings-data-viewer min-h-screen from-slate-900 to-slate-800 bg-gradient-to-br p-6"
  >
    <div class="mx-auto max-w-7xl">
      <!-- 标题 -->
      <div class="mb-8 text-center">
        <h1 class="mb-2 text-4xl text-cyan-400 font-bold">
          1-19栋生产数据总览
        </h1>
        <p class="text-slate-300">水产养殖生产数据管理系统</p>
      </div>

      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 mb-8 gap-6 md:grid-cols-4">
        <div
          class="border border-cyan-500/20 rounded-lg bg-slate-800/50 p-6 backdrop-blur-sm"
        >
          <div class="text-sm text-cyan-400 font-medium">总楼栋数</div>
          <div class="mt-2 text-3xl text-white font-bold">
            {{ totalStats.totalBuildings }}
          </div>
        </div>
        <div
          class="border border-cyan-500/20 rounded-lg bg-slate-800/50 p-6 backdrop-blur-sm"
        >
          <div class="text-sm text-cyan-400 font-medium">总数据条数</div>
          <div class="mt-2 text-3xl text-white font-bold">
            {{ totalStats.totalItems }}
          </div>
        </div>
        <div
          class="border border-cyan-500/20 rounded-lg bg-slate-800/50 p-6 backdrop-blur-sm"
        >
          <div class="text-sm text-cyan-400 font-medium">平均日龄</div>
          <div class="mt-2 text-3xl text-white font-bold">
            {{ totalStats.averageDayAge }}天
          </div>
        </div>
        <div
          class="border border-cyan-500/20 rounded-lg bg-slate-800/50 p-6 backdrop-blur-sm"
        >
          <div class="text-sm text-cyan-400 font-medium">平均头/斤</div>
          <div class="mt-2 text-3xl text-white font-bold">
            {{ totalStats.averageCountPerJin }}
          </div>
        </div>
      </div>

      <!-- 楼栋选择器 -->
      <div class="mb-6">
        <div class="flex flex-wrap gap-2">
          <button
            v-for="buildingId in 19"
            :key="buildingId"
            @click="selectedBuilding = buildingId"
            :class="[
              'px-4 py-2 rounded-lg font-medium transition-all duration-200',
              selectedBuilding === buildingId
                ? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/25'
                : 'bg-slate-700 text-slate-300 hover:bg-slate-600',
            ]"
          >
            {{ buildingId }}#楼
          </button>
          <button
            @click="selectedBuilding = null"
            :class="[
              'px-4 py-2 rounded-lg font-medium transition-all duration-200',
              selectedBuilding === null
                ? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/25'
                : 'bg-slate-700 text-slate-300 hover:bg-slate-600',
            ]"
          >
            全部
          </button>
        </div>
      </div>

      <!-- 数据表格 -->
      <div
        class="overflow-hidden border border-cyan-500/20 rounded-lg bg-slate-800/50 backdrop-blur-sm"
      >
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead class="bg-slate-700/50">
              <tr>
                <th class="px-6 py-4 text-left text-cyan-400 font-medium">
                  厂区
                </th>
                <th class="px-6 py-4 text-left text-cyan-400 font-medium">
                  车间
                </th>
                <th class="px-6 py-4 text-left text-cyan-400 font-medium">
                  方位
                </th>
                <th class="px-6 py-4 text-left text-cyan-400 font-medium">
                  放养规格
                </th>
                <th class="px-6 py-4 text-left text-cyan-400 font-medium">
                  日龄
                </th>
                <th class="px-6 py-4 text-left text-cyan-400 font-medium">
                  头/斤
                </th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="(item, index) in displayData"
                :key="`${item.factory}-${index}`"
                class="border-t border-slate-700/50 transition-colors hover:bg-slate-700/30"
              >
                <td class="px-6 py-4 text-white font-medium">
                  {{ item.factory }}
                </td>
                <td class="px-6 py-4 text-slate-300">{{ item.workshop }}</td>
                <td class="px-6 py-4 text-slate-300">{{ item.direction }}</td>
                <td class="px-6 py-4 text-slate-300">
                  {{ item.specification }}
                </td>
                <td class="px-6 py-4 text-yellow-400 font-bold">
                  {{ item.dayAge }}
                </td>
                <td class="px-6 py-4 text-yellow-400 font-bold">
                  {{ item.countPerJin }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div
          v-if="totalPages > 1"
          class="flex items-center justify-between border-t border-slate-700/50 px-6 py-4"
        >
          <div class="text-sm text-slate-400">
            显示 {{ (currentPage - 1) * pageSize + 1 }} -
            {{ Math.min(currentPage * pageSize, displayData.length) }} 条，共
            {{ displayData.length }} 条数据
          </div>
          <div class="flex gap-2">
            <button
              @click="currentPage = Math.max(1, currentPage - 1)"
              :disabled="currentPage === 1"
              class="rounded bg-slate-700 px-3 py-1 text-slate-300 disabled:cursor-not-allowed hover:bg-slate-600 disabled:opacity-50"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-slate-300"
              >{{ currentPage }} / {{ totalPages }}</span
            >
            <button
              @click="currentPage = Math.min(totalPages, currentPage + 1)"
              :disabled="currentPage === totalPages"
              class="rounded bg-slate-700 px-3 py-1 text-slate-300 disabled:cursor-not-allowed hover:bg-slate-600 disabled:opacity-50"
            >
              下一页
            </button>
          </div>
        </div>
      </div>

      <!-- 导出按钮 -->
      <div class="mt-6 flex gap-4">
        <button
          @click="exportToConsole"
          class="rounded-lg bg-cyan-600 px-6 py-3 text-white font-medium transition-colors hover:bg-cyan-700"
        >
          在控制台查看详细数据
        </button>
        <button
          @click="downloadJSON"
          class="rounded-lg bg-green-600 px-6 py-3 text-white font-medium transition-colors hover:bg-green-700"
        >
          下载JSON数据
        </button>
        <button
          @click="downloadCSV"
          class="rounded-lg bg-blue-600 px-6 py-3 text-white font-medium transition-colors hover:bg-blue-700"
        >
          下载CSV数据
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { getAllBuildingsData, getBuildingData } from "../data/productionData";
import {
  exportAllBuildingsData,
  exportBuildingsDataAsJSON,
  exportBuildingsDataAsCSV,
} from "../data/buildingsDataExport";

const selectedBuilding = ref<number | null>(null);
const currentPage = ref(1);
const pageSize = ref(50);

// 获取所有数据
const allData = getAllBuildingsData();

// 计算总统计信息
const totalStats = computed(() => {
  const allItems = Object.values(allData).flat();
  return {
    totalBuildings: 19,
    totalItems: allItems.length,
    averageDayAge: Math.round(
      allItems.reduce((sum, item) => sum + item.dayAge, 0) / allItems.length
    ),
    averageCountPerJin: Math.round(
      allItems.reduce((sum, item) => sum + item.countPerJin, 0) /
        allItems.length
    ),
  };
});

// 显示的数据
const displayData = computed(() => {
  if (selectedBuilding.value) {
    return getBuildingData(selectedBuilding.value);
  }
  return Object.values(allData).flat();
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(displayData.value.length / pageSize.value);
});

// 导出到控制台
const exportToConsole = () => {
  exportAllBuildingsData();
};

// 下载JSON
const downloadJSON = () => {
  const data = exportBuildingsDataAsJSON();
  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: "application/json",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "1-19栋生产数据.json";
  a.click();
  URL.revokeObjectURL(url);
};

// 下载CSV
const downloadCSV = () => {
  const csvData = exportBuildingsDataAsCSV();
  const blob = new Blob(["\ufeff" + csvData], {
    type: "text/csv;charset=utf-8",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "1-19栋生产数据.csv";
  a.click();
  URL.revokeObjectURL(url);
};

onMounted(() => {
  console.log("1-19栋数据已加载完成！");
  console.log('点击"在控制台查看详细数据"按钮可查看完整数据');
});
</script>
